package com.jin.spring_boot_learn.concurrent.locks.readwritelock;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读锁可以阻止 写锁
 * 写入很少的情况下，使用 ReentrantReadWriteLock 可能会使写入线程遭遇饥饿问题，也就是写入线程无法竞争到锁定而一直处于等待状态
 */
public class ReadWriteLockTest02 {

    private static final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(false);

    private static volatile Integer var;

    /**
     * 一个线程去写 一个线程去删除 5个线程去读
     */
    static Runnable produce = new Runnable() {
        @Override
        public void run() {
            readWriteLock.writeLock().lock();
            System.out.println("produce获取写锁");
            readWriteLock.writeLock().unlock();
            System.out.println("produce释放写锁");
        }
    };

    static Runnable consumer = new Runnable() {
        @Override
        public void run() {
            readWriteLock.readLock().lock();
            System.out.println("consumer获取写锁");
            try {
                Thread.sleep(1000*5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            readWriteLock.readLock().unlock();
            System.out.println("consumer释放写锁");

        }
    };


    public static void main(String[] args) {
        new Thread(consumer).start();
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(produce).start();
    }


}
